import { ErrCode, ErrMsg } from "../common/ErrCode";
import { IReturnData } from "../interfaces/base.interface";
import { Context } from '@midwayjs/koa';
import { Inject } from "@midwayjs/decorator";
import { JwtService } from "@midwayjs/jwt";
import { Tools } from "../common/Tools";

export class ControllerBase{

    @Inject()
    public ctx: Context;
    
    @Inject()
    public jwt:JwtService

    public async makeToken(payload:any):Promise<any>{
        payload = Tools.clone(payload);
        if(payload != null){
            let to = await this.jwt.sign(payload);
            return {
                token:to
            }
        }
        return payload;
    }

    public async ReturnData(code,data:any = null,msg:string = null):Promise<IReturnData<any>>{
        let token = await this.makeToken(data);
        let res:IReturnData<any> = {
            code:code,
            message:msg == null?ErrMsg[code]:msg,
            result:this.resultmsg(code),
            data:token
        }
        return res;
    }

    private resultmsg(code:ErrCode):string{
        switch(code){
            case ErrCode.USER_LGIN_FAIL_PWD:
            case ErrCode.USER_NOT_FOUND:
            case ErrCode.USER_REG_FAIL:
            case ErrCode.USER_REG_EXIST:
            return 'error';
        }
        return 'success'
    }
}